package com.lagou.ModelTest4.Third;

import java.util.concurrent.locks.ReentrantLock;

public class TrainThreadTest extends Thread{
    public static int balance;//用于描述火车票的数量
    private static Demo dm=new Demo();
    private ReentrantLock lock=new ReentrantLock();//准备了一把锁
    public  TrainThreadTest(){}
    public  TrainThreadTest(int balance){
        setBalance(balance);
    }
    public static int getBalance(){
        return balance;
    }
    public void setBalance(int balance){this.balance=balance;
    }
    public void run(){
        //synchronized (TrainThreadTest.class){
        //开始加锁
        //lock.lock();
        //由源码可知:最终是art对象来调用run方法，因此当前正在调用的对象就是art,也就是说this就是art
        //synchronized (this) {
            System.out.println("线程" + Thread.currentThread().getName() + "已启动...");
            synchronized (dm) {
            //synchronized (new Demo()) {  //锁不住 要求必须是同一个对象
            //1.模拟从后台查询火车票数的过程
            int temp = getBalance();
            //2.模拟取票20张的过程
            if (temp >= 20) {
                System.out.println("正在取票，不要急...");
                temp = temp - 20;
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("请取走您的火车票!");
            } else {
                System.out.println("火车票不足!");
            }
            //3.模拟将最新的火车票数写入到后台
            setBalance(temp);
            //lock.unlock();//实现解锁
        }
    }


    public static void main(String[] args) {
        TrainThreadTest t1=new TrainThreadTest(100);
        t1.start();
        TrainThreadTest t2=new TrainThreadTest(100);
        t2.start();
        TrainThreadTest t3=new TrainThreadTest(100);
        t3.start();
        System.out.println("主线程开始等待...");
        try {
            t1.join();
            //t2.start();//等待线程一取款操作结束后再启动线程二
            t2.join();
            t3.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("最终的火车票数为:"+t1.getBalance());//40
    }
}